package org.example.shoppingsystem.controller;
import org.example.shoppingsystem.service.UserService;
import org.example.shoppingsystem.service.UserServiceImpl;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.SQLException;

@Controller
public class LoginController {
    private UserService userService = new UserServiceImpl();

    @GetMapping("/login03")
    public String showLoginPage() {
        return "login";
    }

    @PostMapping("/login03")
    public String login(@RequestParam("username") String username, @RequestParam("pass") String pass, Model model, HttpServletRequest request) {
        String errMsg = "";
        try {
            if (userService.login(username, pass)) {
                HttpSession session = request.getSession(true);
                session.setAttribute("name", username);
                return "welcome";
            } else {
                errMsg += "您的用户名密码不符合,请重新输入";
            }
        } catch (SQLException e) {
            errMsg += "数据库操作出错，请稍后再试。";
            e.printStackTrace();
        }

        if (!errMsg.isEmpty()) {
            model.addAttribute("err", errMsg);
            return "login";
        }
        return "login";
    }
}
